package com.pandora.common.util;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author developer
 */
public class SignatureMaker {

    /**
     * RSA签名
     *
     * @param content 待签名数据
     * @return 签名值
     */
    public static String sign(String content) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(Constants.PRIVATE_KEY);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(Constants.SIGN_RSA);
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

            Signature signature = Signature.getInstance(Constants.SIGN_ALGORITHMS);
            signature.initSign(privateKey);
            signature.update(content.getBytes(Constants.SIGN_CHARSET));

            byte[] signed = signature.sign();
            return Base64.getEncoder().encodeToString(signed).replace("\n", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean verify(String content, String sign, String pubKey) {
        try {
            if(sign.contains(MagicConst.NEW_LINE)){
                sign = sign.replaceAll(MagicConst.NEW_LINE, "");
            }
            KeyFactory keyFactory = KeyFactory.getInstance(Constants.SIGN_RSA);
            byte[] encodeKey = Base64.getDecoder().decode(pubKey);
            PublicKey pKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodeKey));

            Signature signature = Signature.getInstance(Constants.SIGN_ALGORITHMS);

            signature.initVerify(pKey);
            signature.update(content.getBytes(Constants.SIGN_CHARSET));
            boolean bVerify = signature.verify(Base64.getDecoder().decode(sign));
            return bVerify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getSignContent(String appId, String appSecret, String ts) {
        return "app_id=" + appId + "&app_secret=" + appSecret + "&ts=" + ts;
    }

}
